package com.demo.villageresidence.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.villageresidence.dto.Result;
import com.demo.villageresidence.pojo.Feedback;
import com.demo.villageresidence.pojo.FeedbackReply;
import com.demo.villageresidence.pojo.VehicleApply;
import com.demo.villageresidence.service.FeedbackReplyService;
import com.demo.villageresidence.service.FeedbackService;
import com.demo.villageresidence.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/feedback")
public class FeedbackController {


    @Autowired
    private FeedbackService feedbackService;

    @Autowired
    private FeedbackReplyService feedbackReplyService;

    @Autowired
    private UserService userService;

    @GetMapping("getFeedbackPage")
    public Result getFeedbackPage(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                  @RequestParam(value = "pageSize", defaultValue = "10")  Integer pageSize) {


        Page<Feedback> page = feedbackService.query().eq("feed_status", 0)
                .page(new Page<>(current, pageSize));

        // 根据用户id查找用户
        page.getRecords().forEach(feedback -> {
            feedback.setUser(userService.getById(feedback.getUserId()));
        });


        // 获取当前页数据
        List<Feedback> feedbackList = page.getRecords();


        return Result.ok(feedbackList);
    }



    @GetMapping("getFeedbackById/{id}")
    public Result getFeedbackById(@PathVariable("id") Integer id){
        Feedback feedback = feedbackService.getById(id);
        feedback.setUser(userService.getById(feedback.getUserId()));
        return Result.ok(feedback);
    }

    @PostMapping("addFeedback")
    public Result addFeedback(@RequestBody Feedback feedback){
        feedback.setFeedStatus(0);
        feedback.setIsDelete(0);
        feedback.setFeedTime(LocalDateTime.now());

        if (feedbackService.save(feedback)) {
            FeedbackReply feedbackReply = new FeedbackReply();
            feedbackReply.setFeedId(feedback.getFeedId());
            feedbackReply.setIsDelete(0);
            feedbackReplyService.save(feedbackReply);
            return Result.ok("提交成功");
        } else {
            return Result.fail("提交失败");
        }
    }

    @GetMapping("getFeedbackNum")
    public Result getFeedbackNum(){
        Integer feedStatus = feedbackService.query().eq("feed_status", 0).count();
        if (feedStatus>0) {
            return Result.ok(feedStatus);
        }else {
            return Result.ok(0);
        }

    }
}
